package cn.hanyx.coder.core.concurrent.sync;

/**
 * SynchronizedTest01
 *
 * @author hanyx
 * @date 2020/09/23
 */
public class SynchronizedTest02 {

    public synchronized void method1() {
        System.out.println("method1 start");
        try {
            System.out.println("method1 execute");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("method1 end");
    }

    public synchronized void method2() {
        System.out.println("method2 start");
        try {
            System.out.println("method2 execute");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("method2 end");
    }

    /**
     * 分析：可以看出其他线程来访问synchronized修饰的其他方法时需要等待线程1先把锁释放
     */
    public static void main(String[] args) throws InterruptedException {
        SynchronizedTest02 test01 = new SynchronizedTest02();
        Thread t1 = new Thread(test01::method1);
        Thread t2 = new Thread(test01::method2);
        t1.start();
        t2.start();
    }
}
